// 函数组件
import { ExclamationCircleFilled } from "@ant-design/icons";
import { Button, Collapse, DatePicker, Form, Input, message, Modal, Select, Space, Switch, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import type { TableRowSelection } from "antd/es/table/interface";
import { useEffect, useState } from 'react';
import { useNavigate } from "react-router-dom";
import "../../../../src/App.css";
import { getUserList, inquire, modification, moneyinverted, moneyOrder, staTe, timeinverted, timeOrder, userDelete } from "../../../api/userApi"; //引入结构接口
import getSelectTime from "../../../utils/date";
import "./userCss/UserList.css";
// 定义数据类型
interface Type {
  userId: number;
  userName: string;
  userAccount: string;
  userPhone: number;
  regTime: string;
  userBuyMoney: number;
  status: number;
}

//列表方法
function UserList() {
const [form] = Form.useForm();
const [amend,setAmend] = useState(Object);//装修改内容

  const { Panel } = Collapse;
  const { confirm } = Modal;
  const [data, setData] = useState<Type[]>([]);
  // 请求列表数据
  useEffect(() => {
    getUserData();
  }, []);

  // 获取数据
  const getUserData = async () => {
    try {
      let res = await getUserList();
      // console.log('进入了res');
      if (res.code == "200") {
        console.log("1111111", res);
        setData(res.data);
      }
    } catch (err) {
      console.log(err);
    }
  };

  const navigate = useNavigate();
  let flag;
  // 表格列
  const columns: ColumnsType<Type> = [
    {
      title: "序号",
      dataIndex: "userId",
      width: "7%",
      align: "center",
    },
    {
      title: "用户昵称",
      dataIndex: "userName",
      align: "center",
    },
    {
      title: "用户账号",
      dataIndex: "userAccount",
      align: "center",
    },
    {
      title: "手机号",
      dataIndex: "userPhone",
      align: "center",
    },
    {
      title: "注册时间",
      dataIndex: "regTime",
      align: "center",
    },
    {
      title: "消费金额",
      dataIndex: "userBuyMoney",
      align: "center",
    },
    {
      title: "用户可用状态",
      dataIndex: "status",
      align: "center",
      render: (_, record: any) => {
         return ( //这个是加一个选中或者没选中的值defaultChecked
        <Switch
        onClick={()=>{
          condition(record) }}
        defaultChecked={record.status===1?true:false}
        />
        )
        }
    },
    {
      title: "操作",
      dataIndex: "operation",
      align: "center",
      width: "20%",
      render: (value, record) => (
        <div>
          {/* <button className='edit' onClick={() => clickMod(record)}>查看</button> */}
          <button
            onClick={() => {
              goDetails(value);
            }}
            className="inquire1"
          >
            查看
          </button>
          <button className="edit" 
          onClick={() =>{
            showModal(record)
            }}>编辑</button>
          <button
            className="del-left"
            onClick={() => {
              showPromiseConfirm(record);
            }}
           >
            删除
          </button>
        </div>
      ),
    },
  ];

  // 表格选项
  const rowSelection: TableRowSelection<Type> = {
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: "odd",
        text: "Select Odd Row",
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          // setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: "even",
        text: "Select Even Row",
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
        },
      },
    ],
  };

  //1、点击跳转详情页面
  const goDetails = (value: {}) => {
    navigate("/home/user/userDetails");
  };

  // 4、删除函数
  const showPromiseConfirm = (record:any) => {
    console.log('打印传输的数据',record);
    
    confirm({
      title: "确认删除此信息",
      icon: <ExclamationCircleFilled />,
      content: "删除该数据",
      onOk() {
        userDelete(
          [record.userId]
        ).then(res=>{
          if (res.data.code == 200) {
           message.success('删除成功！')
           } else {
            message.info('删除失误啦！')
            }
            getUserData()
          }).catch(err => {
            console.log('err错误了哟', err);
        })
      },
      onCancel() {},
    });
  };
//批量删除
const batch=()=>{
  confirm({
    title: "确认删除此信息",
    icon: <ExclamationCircleFilled />,
    content: "删除该数据",
    onOk() {
      // userDelete(
      //   // [record.userId]
      // ).then(res=>{
      //   if (res.data.code == 200) {
      //    message.success('删除成功！')
      //    } else {
      //     message.info('删除失误啦！')
      //     }
      //     getUserData()
      //   }).catch(err => {
      //     console.log('err错误了哟', err);
      // })
    },
    onCancel() {},
  });
}
// 修改弹框初始值设置
  useEffect(()=>{
    form.setFieldsValue({
       name:amend.userName,
        detailed:amend.userPhone,
        state:amend.status,
    })
    // console.log('gengg',amend);
  },[amend])
  // 修改弹框
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 编辑函数
    const showModal = (record: any) => {
      console.log('打印数据哟',record);
      setAmend(record)
      setIsModalOpen(true);
      
    };
  
    const handleOk = (val:any) => {
      console.log(val);
      modification({
        userId: amend.userId,
        userName:val.name,
        userPhone: val.detailed,
      }).then(res=>{
        message.success('修改成功！')
        // console.log('45454656,',res)
        getUserData()
      }).catch(err=>{
        console.log('err',err);
      })
      setIsModalOpen(false);
    };
  
    const handleCancel = () =>{
      setIsModalOpen(false);
    };
  //// 查询
  const Bemand= async (values:any)=>{
    console.log('打印values',values, getSelectTime(values.stateTime))
    inquire({
			regTime:getSelectTime(values.stateTime), //创建时间
			userPhone:(values.keyword),
			userName:(values.keyword1),
		}).then(res=>{
			console.log('根据条件查询订单结果res',res.data);
			// setData(res.data);
      if(res.data.length>0){
        
        message.success('查询用户成功')
        setData(res.data);
      }else{
        console.log('成功了哟');
        message.info('没有数据')
      }
		}).catch(err=>{
			console.log('err333',err);
			message.error('服务器错误')
		})

  }
// 重置
// 搜索重置
const resetHandle = (event: any) => {
  // 阻止默认事件
  event.preventDefault()
  console.log('重置');
  // 清空搜索框
  form.setFieldsValue({
          keyword:'',
          keyword1:'',
          stateTime:''
      })
      getUserData()
    }
// 重置重新渲染
// 编辑状态
const condition=(record:any)=>{
console.log('打印数据哈哈哈',record.userId)
staTe({
  userId:record.userId,
  status:record.status?0:1
}).then(res=>{
  console.log('打印数据哈哈哈res',res)
  getUserData()
}).catch(err=>{
  console.log('err',err);
}) 
}
//  排序操作
const handleSort=(value:string)=>{
 console.log('hahahh ',value)
 if(value=='按时间顺序'){
  timeOrder().then(res=>{
    setData(res.data);
  })
  
 }else if(value=='按时间倒序'){
  timeinverted().then(res=>{
    setData(res.data);
  })
  
 }else if(value=='按金额顺序'){
  moneyOrder().then(res=>{
    setData(res.data);
  })
  
 }else {
  moneyinverted().then(res=>{
    setData(res.data);
  })
  
 }
}

  // 结构
  return(
    <div>
      {/* 标题 */}
      <p className="head">用户列表</p>
            {/* 操作部分 */}
            <Collapse className='collapse' defaultActiveKey={['1']}>
                <Panel header="筛选查询" key="1">
                    <div className='operate-wrap'>
                        <div className='operate-left'>
                            <Form className='operate-left operate-left-item' layout="inline" form={form} onFinish={Bemand}>
                                <Form.Item label="用户ID:" className='operate-left-item' name='keyword'>
                                    <Input   placeholder="用户账号/手机号" className='search' />
                                </Form.Item>
                                <Form.Item label="用户昵称:" className='operate-left-item' name='keyword1'>
                                    <Input placeholder="用户昵称" className='search' />
                                </Form.Item>
                                <Form.Item label='注册时间:' className='operate-left-item' name='stateTime'>
                                    <DatePicker showTime />
                                </Form.Item>
                                <Form.Item>
                                    <Button className='inquire operate-left-item' htmlType='submit'>
                                      查询</Button>
                                    <Button className='reset operate-left-item' onClick={resetHandle} >重置</Button>
                                </Form.Item>
                            </Form>
                        </div>
                    </div>
                </Panel>
            </Collapse>
            <div className='table'>
                {/* 表格操作 */}
              <div className="table-p">
              <p className="list-left">数据列表</p>
                <div className='operationTable'>
                    {/* 排序 */}
                    <Form>
                        <Form.Item label='排序：' className='operate-left-item' name='state'>
                            <Space wrap>
                                <Select
                                    // onChange={handleChange}
                                    style={{ width: 120 }}
                                    allowClear
                                    options={[{ value: '按时间顺序', label: '按时间顺序'},{ value: '按时间倒序', label: '按时间倒序' },{ value: '按金额顺序', label: '按金额顺序' },{ value: '按金额倒序', label: '按金额倒序' }] }
                                    className='drop'
                                    onChange={handleSort}
                                />
                            </Space>
                        </Form.Item>
                    </Form>
                    <Button id='del' className='operate-left-item' onClick={batch}>批量删除</Button>
                    <Button className='add' >导出</Button>
                </div>
              </div>
                {/* 表格 */}
                <Table 
                rowKey={(item) => item.userId}
                rowSelection={rowSelection} 
                columns={columns} 
                dataSource={data} 
                pagination={{ pageSize: 5 }}  
                className='table-context'/>
            </div>
          {/* 编辑弹框 */}
        
      <Modal title="编辑" open={isModalOpen} onCancel={handleCancel} footer={null}>
      <Form
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
          autoComplete="off"
          form={form} onFinish={handleOk}
        >
          {/* <Form.Item label="序号" name='Id'>
          <Input/>
          </Form.Item> */}
          <Form.Item label="用户昵称" name='name'   >
            <Input placeholder="请输入用户昵称" />
          </Form.Item>
          <Form.Item label="用户手机号" name='detailed'  >
            <Input placeholder="请输手机号" />
          </Form.Item>
          {/* <Form.Item label="上架" valuePropName="checked" name='state' initialValue={amend.status}>
            <Switch  onClick={condition}/>
          </Form.Item>  */}
          <Form.Item wrapperCol={{ offset: 8, span: 16 }} className='opreate'>
            <Button type="primary" htmlType="submit" className='submit'>提交</Button>
            <Button type="primary" onClick={handleCancel} className='cancel'>取消</Button>
          </Form.Item>
        </Form>                      
      </Modal>
    </div>
  )
}

export default UserList;
